package cn.ssdcc.dkserver.util;

import cn.ssdcc.dkserver.exception.BusinessException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Service
@Slf4j
public class DownloadUtil {
    public void downloadNet(String urlstr,String path){
        // 下载网络文件
        try {
            int bytesum = 0;
            int byteread = 0;
            URL url = new URL(urlstr);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(path);
            byte[] buffer = new byte[1204];
            log.info("正在下载:"+urlstr);
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            log.info("完成下载:"+urlstr);
        } catch (FileNotFoundException e) {
            log.error("FileNotFoundException",e);
            throw new BusinessException("下载失败");
        } catch (MalformedURLException e) {
            log.error("MalformedURLException",e);
            throw new BusinessException("下载失败");
        } catch (IOException e) {
            log.error("IOException",e);
            throw new BusinessException("下载失败");
        }
    }

    public String clearPath(String path){
        path = path.replaceAll("/","").
                replaceAll("[?]","").
                replaceAll("[*]","").
                replaceAll(":","").
                replaceAll("\"","").
                replaceAll("<","").
                replaceAll(">","").
                replaceAll("[|]","");
        return path;
    }

    public static void main(String[] args){
        DownloadUtil downloadUtil = new DownloadUtil();
        downloadUtil.downloadNet("","");
    }
}
